# -*- coding:utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
from config.app import get_config
import io
import os
import random
import base64


class CaptchaService:
    """
    验证码模块服务层
    """

    @classmethod
    def generate_captcha(cls, type: str = "math", length: int = 4):

        settings = get_config()

        # 创建空白图像
        image = Image.new('RGB', (500, 300), color='#EAEAEA')

        # 创建绘图对象
        draw = ImageDraw.Draw(image)

        colors = ['red', 'green', 'blue', 'yellow', 'magenta', 'cyan', 'pink', 'brown']
        # 设置字体
        font = ImageFont.truetype(os.path.join(os.path.abspath(os.getcwd()), 'data', 'font', 'Arial.ttf'), size=100)

        result = ""

        if type == "math":
            # 生成两个0-9之间的随机整数
            num1 = random.randint(0, 9)
            num2 = random.randint(0, 9)
            # 从运算符列表中随机选择一个
            operational_character_list = ['+', '-', '*', '/']
            operational_character = random.choice(operational_character_list)
            # 根据选择的运算符进行计算
            if operational_character == '+':
                result = num1 + num2
            elif operational_character == '-':
                result = num1 - num2
            elif operational_character == '*':
                result = num1 * num2
            else:
                result = num1 + 1
                num1 = (num1 + 1) * num2
            # 绘制文本
            text = f"{num1} {operational_character} {num2} = {result}"
            draw.text((30, 120), text, fill='blue', font=font)
        elif type == "text":
            result = ''
            for i in range(length):
                c = random.choice("0123456789abcdefghikjlmnopqrstuvwxyz01234567890123456789012345678901234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
                result += c

                draw.text((50 + i * 100, 80 + random.randint(0, 40)), c, fill=random.choice(colors), font=font)

        # 将图像数据保存到内存中
        buffer = io.BytesIO()
        image.save(buffer, format='PNG')

        # 将图像数据转换为base64字符串
        base64_string = f'data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode()}'

        return base64_string, result.lower()
